package redis

import (
	"github.com/astaxie/beego"
	"github.com/go-redis/redis"
	"log"
	"strings"
)

var RedisMap map[string]*redis.Client

func init() {
	log.Println("init redis client ...")
	RedisMap = make(map[string]*redis.Client)
	dbstr := beego.AppConfig.String("redislist")
	dblist := strings.Split(dbstr, ",")
	for _, item := range dblist {
		Pwd := beego.AppConfig.String(item + ".redis.password")
		Host := beego.AppConfig.String(item + ".redis.host")
		Db, e := beego.AppConfig.Int(item + ".redis.db")
		if e != nil {
			log.Println("获取Db失败！", e)
			return
		}
		client, e := RedisInit(Host, Pwd, Db)
		if e != nil {
			log.Println("redis客户端初始化失败！", e)
			continue
		}
		RedisMap[item] = client
		log.Println(item + " inited!")
	}
	log.Println("redis client map初始化完成！", RedisMap)
}

func RedisInit(addr string, pwd string, db int) (*redis.Client, error) {
	redisdb := redis.NewClient(&redis.Options{
		Addr:     addr,
		Password: pwd,
		DB:       db,
		PoolSize: 10,
	})
	_, err := redisdb.Ping().Result()
	if err != nil {
		return nil, err
	} else {
		return redisdb, nil
	}
}
